package nio.tcp.server_client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

public class Server {

    public static final String localCharsetName = "utf-8";
    public static final int listener_port = 8888;
    public static final int buffer_size = 1024;
    public static final int time_out = 1000;

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.socket().bind(new InetSocketAddress(listener_port));
        serverChannel.configureBlocking(false);

        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {  //有这个while，导致nio不好用，所以有了aio

            if (selector.select(time_out) == 0) {
                System.out.print(".");
                continue;
            }
            System.out.println();

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {

                SelectionKey key = keyIter.next();

                //有客户端连接过来，准备一个channel与之通信
                if (key.isAcceptable()) {
                    SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
                    clientChannel.configureBlocking(false);
                    clientChannel.register(key.selector(), SelectionKey.OP_READ,
                            ByteBuffer.allocate(buffer_size)); //附加一个ByteBuffer在上面
                }

                //客户端有写入时
                if (key.isReadable()) {
                    SocketChannel clientChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    buffer.clear();

                    long readCount = clientChannel.read(buffer);
                    if (readCount == -1) {
                        clientChannel.close();
                    } else {
                        buffer.flip();
                        String receiveString = Charset.forName(localCharsetName).newDecoder().decode(buffer).toString();
                        System.out.println("接收到的信息：" + receiveString);
                        String sendString = "你好，客户端。已经收到你的信息：" + receiveString;
                        buffer = ByteBuffer.wrap(sendString.getBytes(localCharsetName));
                        while (buffer.hasRemaining()) {
                            clientChannel.write(buffer);
                        }
                        key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    }
                }
                keyIter.remove();
            }
        }
    }
}
